package com.sxbbc.common.core.service.system.redis.listener;

import com.sxbbc.common.core.service.system.redis.RedisExpirationservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import com.sxbbc.common.core.enums.redis.RedisExpiredEnums;

/**
 * @author arno
 * @Description: 监听redis的key失效
 * 单例防止重复实例化
 */
@Component
public class RedisKeyExpirationListener implements MessageListener {
    @Autowired
    private RedisExpirationservice redisExpirationservice;

    public static RedisKeyExpirationListener redisKeyExpirationListener = null;

    public static RedisKeyExpirationListener getInstance() {
    	System.out.println("redis监听实例创建");
        if (redisKeyExpirationListener == null) {
            synchronized (RedisKeyExpirationListener.class) {
                if (redisKeyExpirationListener == null) {
                    redisKeyExpirationListener = new RedisKeyExpirationListener();
                    System.out.println("redis启动监听失效键值对");
                }
            }
        }
        return redisKeyExpirationListener;
    }

    public void onMessage(Message message, byte[] pattern) {
        System.out.println("channel:" + new String(message.getChannel())
                + ",message:" + new String(message.getBody()));
        //事件渠道 为过期监听
        String channel = new String(message.getChannel());
        if ("__keyevent@0__:expired".equals(channel)) {
            //获取到过期key 做业务逻辑处理
            String key = new String(message.getBody());
            String eventType = key;
            String params = "";
            //如果有分隔
            if (key.indexOf("_") > -1) {
                String[] keySplit = key.split("_");
                //业务类型
                eventType = keySplit[0] + "_";
                params = keySplit[1];
            }
            RedisExpiredEnums enums = RedisExpiredEnums.getEnums(eventType);
            System.out.println("redis监听拿到的eventType业务类型：" + eventType);
            if (enums != null) {
                //处理事件
                redisExpirationservice.handleExpires(enums, params);
            }
        }
    }
}